package com.sinping.qh.service.common.impl;

import com.google.common.base.Strings;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.repository.mongo.common.UploadImageRepository;
import com.sinping.qh.service.common.FileManagerService;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.pdf.HtmlGenerator;
import com.sinping.qh.utils.pdf.PdfGenerator;
import com.sinping.qh.utils.time.DateFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

/**
 * @author wupeng
 * @create 2018/5/30
 */
@Service
@Slf4j
public class FileManagerServiceImpl implements FileManagerService {

    @Value(value = "${qh.upload.filePath}")
    private String filePath;
    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;

    @Autowired
    private UploadImageRepository imageRepository;

    /**
     * 上传图片
     *
     * @param roleId     角色id
     * @param originName 图片原始名称
     * @param fileType   图片类型
     * @param content    图片
     * @param remark     备注
     * @return 图片Id
     */
    @Override
    public String saveImage(String roleId, String originName, String fileType, byte[] content, String remark) {

        if (Strings.isNullOrEmpty(roleId)) {
            log.error("保存图片 隐患/亮点记录Id 不存在");
            return null;
        }

        if (Strings.isNullOrEmpty(originName)) {
            log.error("保存图片 文件原名 不存在");
            return null;
        }

        if (content == null || content.length == 0) {
            log.error("保存图片 内容 不存在");
            return null;
        }

        String path = "/image/";

        String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());

        String id = IdGenerator.uuid2();
        String newName = id;
        String imageType = null;
        if (originName.lastIndexOf(".") >= 0) {
            imageType = originName.substring(originName.indexOf(".") + 1);
            newName += "." + imageType;
        }
        // 判断传入的fileType和名称后缀是否相同 如果不同 或者为null 则使用imageType
        if (Strings.isNullOrEmpty(fileType) || !fileType.equals(imageType)) {
            fileType = imageType;
        }

        path += roleId + "/" + date + "/";

        //保存文件
        File dir = new File(filePath + path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(filePath + path + newName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(content);
        } catch (IOException e) {
            log.error("文件保存失败", e);
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {/*do nothing*/}
            }
        }

        UploadImage uploadImage = new UploadImage();
        uploadImage.setId(id);
        uploadImage.setRoleId(roleId);
        uploadImage.setOriginName(originName);
        uploadImage.setNewName(newName);

        //保存记录
        uploadImage.setPath(path + newName);
        uploadImage.setType(fileType);
        uploadImage.setSize((long) content.length);
        uploadImage.setRemark(remark);
        uploadImage.setGmtCreated(new Date());
        uploadImage.setGmtModified(new Date());

        uploadImage = imageRepository.save(uploadImage);
        if (null != uploadImage) {
            return uploadImage.getId();
        } else {
            log.error("文件插入数据库失败");
            return null;
        }
    }

    /**
     * 根据图片Id 获取 图片
     *
     * @param id 图片Id
     * @return 图片对象
     */
    @Override
    public UploadImage getImageById(String id) {
        if (Strings.isNullOrEmpty(id)) {
            return null;
        }
        UploadImage uploadImage = imageRepository.findOne(id);
        return uploadImage;
    }


    /**
     * @param id
     * @return
     */
    @Override
    public String getImageUrlById(String id) {
        UploadImage image = getImageById(id);
        if (null == image) {
            return null;
        }

        String url = urlPath + image.getPath();
        log.info("图片下载地址 {}", url);
        return url;
    }

    /**
     * @param id
     * @return
     */
    @Override
    public String getFileOrImageUrlById(String id) {
        UploadImage image = getImageById(id);
        if (null == image) {
            return null;
        }

        String url = image.getPath();
        log.info("图片或文件保存的地址 {}", url);
        return url;
    }

    @Override
    public String saveFile(String roleId, String originName, String fileType, byte[] content, String remark) {
        if (Strings.isNullOrEmpty(roleId)) {
            log.error("保存文件 角色Id 不存在");
            return null;
        }

        if (Strings.isNullOrEmpty(originName)) {
            log.error("保存文件 文件原名 不存在");
            return null;
        }

        if (content == null || content.length == 0) {
            log.error("保存文件 内容 不存在");
            return null;
        }

        String path = "/file/";

        String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());

        String id = IdGenerator.uuid2();
        String newName = id;
        String imageType = null;
        if (originName.lastIndexOf(".") >= 0) {
            imageType = originName.substring(originName.indexOf(".") + 1);
            newName += "." + imageType;
        }
        // 判断传入的fileType和名称后缀是否相同 如果不同 或者为null 则使用imageType
        if (Strings.isNullOrEmpty(fileType) || !fileType.equals(imageType)) {
            fileType = imageType;
        }

        path += roleId + "/" + date + "/";

        //保存文件
        File dir = new File(filePath + path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file;
        if (imageType.equals("xls") || imageType.equals("xlsx")) {
            String xlsPath = "/var/www/images/qh/file/1/2018/8a4dc660c16187b18ed65a8ed9ebd09e.xls";
            file = new File(xlsPath);
        } else {
            file = new File(filePath + path + newName);
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(content);
        } catch (IOException e) {
            log.error("文件保存失败", e);
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {/*do nothing*/}
            }
        }

        UploadImage uploadImage = new UploadImage();
        uploadImage.setId(id);
        uploadImage.setRoleId(roleId);
        uploadImage.setOriginName(originName);

        //保存记录
        if (imageType.equals("xls") || imageType.equals("xlsx")) {
            uploadImage.setNewName("8a4dc660c16187b18ed65a8ed9ebd09e.xls");
            uploadImage.setPath("/file/1/2018/8a4dc660c16187b18ed65a8ed9ebd09e.xls");
        } else {
            uploadImage.setNewName(newName);
            uploadImage.setPath(path + newName);
        }
        uploadImage.setType(fileType);
        uploadImage.setSize((long) content.length);
        uploadImage.setRemark(remark);
        uploadImage.setGmtCreated(new Date());
        uploadImage.setGmtModified(new Date());

        uploadImage = imageRepository.save(uploadImage);
        if (null != uploadImage) {
            return uploadImage.getId();
        } else {
            log.error("文件插入数据库失败");
            return null;
        }
    }

    @Override
    public String savePdfByNotice(String roleId, String originName, String fileType, Map<String, Object> variables, String remark) {

        try {
            if (Strings.isNullOrEmpty(roleId)) {
                log.error("保存文件 角色Id 不存在");
                return null;
            }

            if (Strings.isNullOrEmpty(originName)) {
                log.error("保存文件 文件原名 不存在");
                return null;
            }
            String path = "/pdf/";

            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());

            String id = IdGenerator.uuid2();
            String newName = id;
            String imageType = null;
            if (originName.lastIndexOf(".") >= 0) {
                imageType = originName.substring(originName.indexOf(".") + 1);
                newName += "." + imageType;
            }
            // 判断传入的fileType和名称后缀是否相同 如果不同 或者为null 则使用imageType
            if (Strings.isNullOrEmpty(fileType) || !fileType.equals(imageType)) {
                fileType = imageType;
            }

            path += roleId + "/" + date + "/";
            //保存文件
            File dir = new File(filePath + path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //生成pdf,保存起来
            String htmlStr = HtmlGenerator.generate("notice.html", variables);

            OutputStream out = new FileOutputStream(filePath + path + newName);
            PdfGenerator.generatePlus(htmlStr, out, urlPath);

            UploadImage uploadImage = new UploadImage();
            uploadImage.setId(id);
            uploadImage.setRoleId(roleId);
            uploadImage.setOriginName(originName);
            uploadImage.setNewName(newName);

            //保存记录
            uploadImage.setPath(path + newName);
            uploadImage.setType(fileType);
            uploadImage.setSize(0l);
            uploadImage.setRemark(remark);
            uploadImage.setGmtCreated(new Date());
            uploadImage.setGmtModified(new Date());

            uploadImage = imageRepository.save(uploadImage);
            if (null != uploadImage) {
                return uploadImage.getId();
            } else {
                log.error("文件插入数据库失败");
                return null;
            }
        } catch (Exception e) {
//           int a=1;
        }
        return null;
    }

    @Override
    public String getFileById(String id) {
        UploadImage image = getImageById(id);
        if (null == image) {
            return null;
        }

        String url = urlPath + image.getPath();
        log.info("文件下载地址 {}", url);
        return url;
    }
//
//    @Override
//    public ResDto deleteById(String id) {
//
//        UploadImage uploadImage = imageRepository.findOne(id);
//        if (uploadImage==null){
//            return new ResDto(ConstEum.SERVER_ERROR,"图片不存在");
//        }
//        if (uploadImage!=null){
//            imageRepository.delete(uploadImage.getId());
//
//        }
//        return new ResDto(Const.SUCCESS,"删除成功");
//
//    }

}
